package com.luo.backend.service;

import com.luo.backend.dto.*;
import com.luo.backend.entity.*;
import com.luo.backend.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 团购服务类
 */
@Service
public class GroupBuyingService {
    
    private static final Logger logger = LoggerFactory.getLogger(GroupBuyingService.class);
    
    @Autowired
    private GroupBuyingActivityRepository activityRepository;
    
    @Autowired
    private GroupBuyingParticipantRepository participantRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;
    
    @Autowired
    private UserAddressRepository addressRepository;
    
    /**
     * 发起团购
     */
    @Transactional
    public GroupBuyingResponse createGroupBuying(Long userId, CreateGroupBuyingRequest request) {
        logger.info("用户{}发起团购", userId);
        
        // 验证商品
        Optional<Food> foodOpt = foodRepository.findById(request.getFoodId());
        if (!foodOpt.isPresent()) {
            throw new RuntimeException("商品不存在");
        }
        Food food = foodOpt.get();
        
        // 验证商家
        Optional<Merchant> merchantOpt = merchantRepository.findById(food.getMerchantId());
        if (!merchantOpt.isPresent()) {
            throw new RuntimeException("商家不存在");
        }
        Merchant merchant = merchantOpt.get();
        
        // 验证参数
        if (request.getMinParticipants() > request.getMaxParticipants()) {
            throw new RuntimeException("最少参与人数不能大于最多参与人数");
        }
        
        // ✅ 使用前端传入的价格，不再计算8折（避免双重折扣）
        BigDecimal originalPrice = request.getOriginalPrice();
        BigDecimal groupPrice = request.getGroupPrice();
        
        // 如果前端没传价格，使用商品价格作为fallback（向后兼容）
        if (originalPrice == null) {
            originalPrice = food.getOriginalPrice() != null ? 
                food.getOriginalPrice() : food.getPrice();
            logger.warn("前端未传递originalPrice，使用商品原价: {}", originalPrice);
        }
        if (groupPrice == null) {
            groupPrice = food.getPrice();
            logger.warn("前端未传递groupPrice，使用商品折后价: {}", groupPrice);
        }
        
        // 创建团购活动
        GroupBuyingActivity activity = new GroupBuyingActivity();
        activity.setInitiatorUserId(userId);
        activity.setFoodId(food.getId());
        activity.setMerchantId(merchant.getId());
        activity.setTitle(request.getTitle());
        activity.setDescription(request.getDescription());
        activity.setMinParticipants(request.getMinParticipants());
        activity.setMaxParticipants(request.getMaxParticipants());
        activity.setCurrentParticipants(1); // 发起人自动参与
        activity.setOriginalPrice(originalPrice);  // ✅ 使用真正的原价
        activity.setGroupPrice(groupPrice);  // ✅ 使用拼单价（不再额外打折）
        activity.setStartTime(LocalDateTime.now());
        activity.setEndTime(LocalDateTime.now().plusHours(request.getDurationHours()));
        activity.setStatus("active");
        
        activity = activityRepository.save(activity);
        
        // 发起人自动参与团购
        GroupBuyingParticipant participant = new GroupBuyingParticipant();
        participant.setActivityId(activity.getId());
        participant.setUserId(userId);
        participant.setQuantity(request.getQuantity());
        participant.setSpiceLevel(request.getSpiceLevel());
        participant.setStatus("joined");
        participant.setJoinedAt(LocalDateTime.now()); // 修复：设置团长的加入时间
        
        participantRepository.save(participant);
        
        logger.info("团购活动创建成功: {}", activity.getId());
        return buildGroupBuyingResponse(activity, userId);
    }
    
    /**
     * 参与团购
     */
    @Transactional
    public GroupBuyingResponse joinGroupBuying(Long userId, Long activityId, JoinGroupBuyingRequest request) {
        logger.info("用户{}参与团购{}", userId, activityId);
        
        // 验证团购活动
        Optional<GroupBuyingActivity> activityOpt = activityRepository.findById(activityId);
        if (!activityOpt.isPresent()) {
            throw new RuntimeException("团购活动不存在");
        }
        GroupBuyingActivity activity = activityOpt.get();
        
        // 验证团购状态
        if (!"active".equals(activity.getStatus())) {
            throw new RuntimeException("团购活动已结束");
        }
        
        // 验证是否过期
        if (LocalDateTime.now().isAfter(activity.getEndTime())) {
            throw new RuntimeException("团购活动已过期");
        }
        
        // 验证人数限制
        if (activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            throw new RuntimeException("团购人数已满");
        }
        
        // 验证是否已参与（排除已取消的参与记录）
        Optional<GroupBuyingParticipant> activeParticipant = 
            participantRepository.findActiveParticipantByActivityIdAndUserId(activityId, userId);
        if (activeParticipant.isPresent()) {
            throw new RuntimeException("您已参与该团购");
        }
        
        // 检查是否存在已取消的参与记录
        Optional<GroupBuyingParticipant> cancelledParticipant = 
            participantRepository.findByActivityIdAndUserId(activityId, userId);
        
        GroupBuyingParticipant participant;
        if (cancelledParticipant.isPresent() && "cancelled".equals(cancelledParticipant.get().getStatus())) {
            // 如果之前退出过，更新旧记录而不是插入新记录
            participant = cancelledParticipant.get();
            participant.setQuantity(request.getQuantity());
            participant.setSpiceLevel(request.getSpiceLevel());
            participant.setStatus("joined");
            participant.setJoinedAt(LocalDateTime.now());
            logger.info("用户{}重新参与团购{}，更新已取消的记录", userId, activityId);
        } else {
            // 首次参与，创建新记录
            participant = new GroupBuyingParticipant();
            participant.setActivityId(activityId);
            participant.setUserId(userId);
            participant.setQuantity(request.getQuantity());
            participant.setSpiceLevel(request.getSpiceLevel());
            participant.setStatus("joined");
            logger.info("用户{}首次参与团购{}", userId, activityId);
        }
        
        participantRepository.save(participant);
        
        // 更新参与人数
        activity.setCurrentParticipants(activity.getCurrentParticipants() + 1);
        activityRepository.save(activity);
        
        // ========== 🆕 核心逻辑：检查是否成团并自动创建订单 ==========
        // ⭐ 修复：只有状态为 active 的拼单才能触发成团（防止重复成团）
        if ("active".equals(activity.getStatus()) && 
            activity.getCurrentParticipants() >= activity.getMinParticipants()) {
            logger.info("团购活动{}达到最小成团人数，开始创建订单", activityId);
            
            // 标记拼单成功
            activity.setStatus("success");
            activityRepository.save(activity);
            
            // 为所有参与者创建订单
            createOrdersForParticipants(activity);
            
            logger.info("团购活动{}成团成功，订单已自动创建", activityId);
        }
        // ===============================================================
        
        logger.info("用户{}成功参与团购{}", userId, activityId);
        return buildGroupBuyingResponse(activity, userId);
    }
    
    /**
     * 获取团购列表
     */
    public Map<String, Object> getGroupBuyingList(Long merchantId, int page, int size, Long currentUserId) {
        logger.info("获取团购列表: merchantId={}, page={}, size={}", merchantId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<GroupBuyingActivity> activityPage;
        
        if (merchantId != null) {
            activityPage = activityRepository.findActiveActivitiesByMerchant(merchantId, pageable);
        } else {
            activityPage = activityRepository.findActiveActivities(pageable);
        }
        
        List<GroupBuyingResponse> activities = activityPage.getContent().stream()
            .map(activity -> buildGroupBuyingResponse(activity, currentUserId))
            .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("activities", activities);
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", size);
        pagination.put("total", activityPage.getTotalElements());
        pagination.put("total_pages", activityPage.getTotalPages());
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 获取团购详情
     */
    public GroupBuyingResponse getGroupBuyingDetail(Long activityId, Long currentUserId) {
        logger.info("获取团购详情: activityId={}", activityId);
        
        Optional<GroupBuyingActivity> activityOpt = activityRepository.findById(activityId);
        if (!activityOpt.isPresent()) {
            throw new RuntimeException("团购活动不存在");
        }
        
        GroupBuyingActivity activity = activityOpt.get();
        return buildGroupBuyingResponse(activity, currentUserId);
    }
    
    /**
     * 获取我的团购
     */
    public Map<String, Object> getMyGroupBuying(Long userId, int page, int size) {
        logger.info("获取我的团购: userId={}, page={}, size={}", userId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<GroupBuyingActivity> activityPage = activityRepository.findByInitiatorUserId(userId, pageable);
        
        List<GroupBuyingResponse> activities = activityPage.getContent().stream()
            .map(activity -> buildGroupBuyingResponse(activity, userId))
            .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("activities", activities);
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", size);
        pagination.put("total", activityPage.getTotalElements());
        pagination.put("total_pages", activityPage.getTotalPages());
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 取消团购
     */
    @Transactional
    public GroupBuyingResponse cancelGroupBuying(Long userId, Long activityId) {
        logger.info("取消团购: userId={}, activityId={}", userId, activityId);
        
        Optional<GroupBuyingActivity> activityOpt = activityRepository.findByIdAndInitiatorUserId(activityId, userId);
        if (!activityOpt.isPresent()) {
            throw new RuntimeException("团购活动不存在或您不是发起人");
        }
        
        GroupBuyingActivity activity = activityOpt.get();
        
        if (!"active".equals(activity.getStatus())) {
            throw new RuntimeException("团购活动状态不允许取消");
        }
        
        // 取消团购活动
        activity.setStatus("cancelled");
        activityRepository.save(activity);
        
        // 取消所有参与者
        List<GroupBuyingParticipant> participants = participantRepository.findByActivityIdOrderByJoinedAtAsc(activityId);
        participants.forEach(p -> p.setStatus("cancelled"));
        participantRepository.saveAll(participants);
        
        logger.info("团购取消成功: {}", activityId);
        return buildGroupBuyingResponse(activity, userId);
    }
    
    /**
     * 获取可团购商品
     */
    public Map<String, Object> getGroupBuyingFoods(Long merchantId, int page, int size) {
        logger.info("获取可团购商品: merchantId={}, page={}, size={}", merchantId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Food> foodPage;
        
        if (merchantId != null) {
            foodPage = foodRepository.findByMerchantIdAndStatus(merchantId, 1, pageable);
        } else {
            foodPage = foodRepository.findByStatus(1, pageable);
        }
        
        List<FoodResponse> foods = foodPage.getContent().stream()
            .map(food -> {
                FoodResponse response = new FoodResponse(food);
                // 设置商家信息
                Optional<Merchant> merchantOpt = merchantRepository.findById(food.getMerchantId());
                if (merchantOpt.isPresent()) {
                    Merchant merchant = merchantOpt.get();
                    FoodResponse.MerchantInfo merchantInfo = new FoodResponse.MerchantInfo(
                        merchant.getId(),
                        merchant.getName(),
                        merchant.getMinOrderAmount(),
                        merchant.getDeliveryFee()
                    );
                    response.setMerchant(merchantInfo);
                }
                // 设置分类信息
                if (food.getCategoryId() != null) {
                    // 这里可以添加分类信息的设置
                }
                return response;
            })
            .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("foods", foods);
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", size);
        pagination.put("total", foodPage.getTotalElements());
        pagination.put("total_pages", foodPage.getTotalPages());
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 取消参与团购
     */
    @Transactional
    public GroupBuyingResponse leaveGroupBuying(Long userId, Long activityId) {
        logger.info("用户{}取消参与团购{}", userId, activityId);
        
        // 验证团购活动
        Optional<GroupBuyingActivity> activityOpt = activityRepository.findById(activityId);
        if (!activityOpt.isPresent()) {
            throw new RuntimeException("团购活动不存在");
        }
        GroupBuyingActivity activity = activityOpt.get();
        
        // 验证团购状态
        // ⭐ 修复：如果拼单已成团，不允许退出（避免反复退出/参与导致重复订单）
        if ("success".equals(activity.getStatus())) {
            throw new RuntimeException("拼单已成团，无法退出。如需取消订单，请在订单列表中操作");
        }
        
        if (!"active".equals(activity.getStatus())) {
            throw new RuntimeException("团购活动已结束，无法取消参与");
        }
        
        // 查找参与记录
        Optional<GroupBuyingParticipant> participantOpt = 
            participantRepository.findByActivityIdAndUserId(activityId, userId);
        if (!participantOpt.isPresent()) {
            throw new RuntimeException("您没有参与该团购");
        }
        
        GroupBuyingParticipant participant = participantOpt.get();
        if ("cancelled".equals(participant.getStatus())) {
            throw new RuntimeException("您已经取消参与该团购");
        }
        
        // 不允许发起人取消参与
        if (activity.getInitiatorUserId().equals(userId)) {
            throw new RuntimeException("发起人不能取消参与，只能取消整个团购活动");
        }
        
        // 取消参与
        participant.setStatus("cancelled");
        participantRepository.save(participant);
        
        // 更新参与人数
        Long activeParticipants = participantRepository.countActiveParticipantsByActivityId(activityId);
        activity.setCurrentParticipants(activeParticipants.intValue());
        
        // 如果参与人数不足最少人数，可以考虑将活动状态改为失败
        // 这里暂时保持active状态，让活动自然过期
        
        activityRepository.save(activity);
        
        logger.info("用户{}成功取消参与团购{}", userId, activityId);
        return buildGroupBuyingResponse(activity, userId);
    }
    
    /**
     * 获取我参与的团购列表
     */
    public Map<String, Object> getMyParticipations(Long userId, int page, int size) {
        logger.info("获取用户{}参与的团购列表: page={}, size={}", userId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<GroupBuyingParticipant> participantPage = participantRepository.findByUserId(userId, pageable);
        
        List<GroupBuyingResponse> activities = participantPage.getContent().stream()
            .map(participant -> {
                Optional<GroupBuyingActivity> activityOpt = activityRepository.findById(participant.getActivityId());
                if (activityOpt.isPresent()) {
                    GroupBuyingResponse response = buildGroupBuyingResponse(activityOpt.get(), userId);
                    // 设置我的参与信息
                    response.getParticipants().stream()
                        .filter(p -> p.getUserId().equals(userId))
                        .findFirst()
                        .ifPresent(myParticipation -> {
                            // 可以添加一些我的参与状态信息
                        });
                    return response;
                }
                return null;
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
        
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", size);
        pagination.put("total", participantPage.getTotalElements());
        pagination.put("total_pages", participantPage.getTotalPages());
        
        Map<String, Object> result = new HashMap<>();
        result.put("activities", activities);
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 获取团购活动参与者列表
     */
    public List<GroupBuyingResponse.ParticipantResponse> getActivityParticipants(Long activityId) {
        logger.info("获取团购活动{}的参与者列表", activityId);
        
        // 验证团购活动是否存在
        Optional<GroupBuyingActivity> activityOpt = activityRepository.findById(activityId);
        if (!activityOpt.isPresent()) {
            throw new RuntimeException("团购活动不存在");
        }
        
        // 获取参与者列表
        List<GroupBuyingParticipant> participants = participantRepository.findByActivityIdOrderByJoinedAtAsc(activityId);
        
        return participants.stream()
            .map(participant -> {
                GroupBuyingResponse.ParticipantResponse participantResponse = 
                    new GroupBuyingResponse.ParticipantResponse(participant);
                // 设置用户信息（用户名、真实姓名、头像）
                Optional<User> userOpt = userRepository.findById(participant.getUserId());
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    participantResponse.setUsername(user.getUsername());
                    participantResponse.setRealName(user.getRealName()); // ⭐ 设置真实姓名
                    participantResponse.setAvatar(user.getAvatar()); // ⭐ 设置头像
                }
                return participantResponse;
            })
            .collect(Collectors.toList());
    }
    
    /**
     * 🆕 为所有参与者创建订单
     */
    private void createOrdersForParticipants(GroupBuyingActivity activity) {
        logger.info("开始为拼单活动{}的参与者创建订单", activity.getId());
        
        // 获取所有参与者
        List<GroupBuyingParticipant> participants = participantRepository
            .findByActivityIdOrderByJoinedAtAsc(activity.getId());
        
        // 获取商品信息
        Optional<Food> foodOpt = foodRepository.findById(activity.getFoodId());
        if (!foodOpt.isPresent()) {
            logger.error("商品{}不存在，无法创建订单", activity.getFoodId());
            return;
        }
        Food food = foodOpt.get();
        
        // 获取商家信息
        Optional<Merchant> merchantOpt = merchantRepository.findById(activity.getMerchantId());
        if (!merchantOpt.isPresent()) {
            logger.error("商家{}不存在，无法创建订单", activity.getMerchantId());
            return;
        }
        Merchant merchant = merchantOpt.get();
        
        int successCount = 0;
        for (GroupBuyingParticipant participant : participants) {
            try {
                // 跳过已经有订单的参与者
                if (participant.getOrderId() != null) {
                    logger.info("参与者{}已有订单，跳过", participant.getUserId());
                    continue;
                }
                
                // 跳过已取消的参与者
                if ("cancelled".equals(participant.getStatus())) {
                    logger.info("参与者{}已取消，跳过", participant.getUserId());
                    continue;
                }
                
                // 获取用户的默认地址
                UserAddress address = null;
                Optional<UserAddress> defaultAddressOpt = addressRepository
                    .findByUserIdAndIsDefaultTrue(participant.getUserId());
                
                if (defaultAddressOpt.isPresent()) {
                    address = defaultAddressOpt.get();
                } else {
                    // 如果没有默认地址，获取用户的第一个地址
                    List<UserAddress> userAddresses = addressRepository
                        .findByUserIdOrderByIsDefaultDescCreatedAtDesc(participant.getUserId());
                    if (!userAddresses.isEmpty()) {
                        address = userAddresses.get(0);
                        logger.info("用户{}没有默认地址，使用第一个地址", participant.getUserId());
                    }
                }
                
                // 创建订单
                Order order = new Order();
                
                // 生成唯一订单号
                String orderNo;
                do {
                    orderNo = "ORD" + System.currentTimeMillis() + 
                             String.format("%04d", new Random().nextInt(10000));
                } while (orderRepository.existsByOrderNo(orderNo));
                
                order.setOrderNo(orderNo);
                order.setUserId(participant.getUserId());
                order.setMerchantId(activity.getMerchantId());
                order.setMerchantName(merchant.getName());
                
                // 收货地址信息
                if (address != null) {
                    order.setDeliveryName(address.getName());
                    order.setDeliveryPhone(address.getPhone());
                    order.setDeliveryAddress(address.getProvince() + " " + 
                                          address.getCity() + " " + 
                                          address.getDistrict() + " " + 
                                          address.getAddress());
                } else {
                    // 如果用户没有地址，使用空值
                    order.setDeliveryName("待补充");
                    order.setDeliveryPhone("待补充");
                    order.setDeliveryAddress("待补充地址");
                    logger.warn("用户{}没有地址信息，订单地址为空", participant.getUserId());
                }
                
                // 配送信息（默认设置为明天12:00-14:00）
                order.setScheduledDeliveryDate(java.time.LocalDate.now().plusDays(1));
                order.setScheduledDeliveryTime("12:00-14:00");
                
                // 价格信息
                BigDecimal foodAmount = activity.getGroupPrice()
                    .multiply(new BigDecimal(participant.getQuantity()));
                BigDecimal deliveryFee = merchant.getDeliveryFee() != null ? 
                    merchant.getDeliveryFee() : BigDecimal.ZERO;
                order.setFoodAmount(foodAmount);
                order.setDeliveryFee(deliveryFee);
                order.setTotalAmount(foodAmount.add(deliveryFee));
                
                // 订单状态：待支付
                order.setStatus("pending");
                
                // 备注
                order.setNotes("拼单订单 - " + activity.getTitle());
                
                // 保存订单
                order = orderRepository.save(order);
                logger.info("为用户{}创建订单成功: {}", participant.getUserId(), order.getOrderNo());
                
                // 创建订单商品明细
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setFoodId(food.getId());
                orderItem.setFoodName(food.getName());
                orderItem.setFoodImage(food.getImage());
                orderItem.setFoodPrice(activity.getGroupPrice());
                orderItem.setQuantity(participant.getQuantity());
                orderItem.setSpiceLevel(participant.getSpiceLevel());
                orderItem.setSubtotal(foodAmount);
                orderItemRepository.save(orderItem);
                
                // ✅ 关键：更新参与者的订单ID
                participant.setOrderId(order.getId());
                participantRepository.save(participant);
                
                successCount++;
                logger.info("成功为参与者{}创建订单，订单ID: {}", participant.getUserId(), order.getId());
                
            } catch (Exception e) {
                logger.error("为参与者{}创建订单失败", participant.getUserId(), e);
                // 继续为其他参与者创建订单
            }
        }
        
        logger.info("拼单活动{}订单创建完成，成功创建{}个订单", activity.getId(), successCount);
    }
    
    /**
     * 构建团购响应对象
     */
    private GroupBuyingResponse buildGroupBuyingResponse(GroupBuyingActivity activity, Long currentUserId) {
        GroupBuyingResponse response = new GroupBuyingResponse(activity);
        
        // 设置商品信息
        Optional<Food> foodOpt = foodRepository.findById(activity.getFoodId());
        if (foodOpt.isPresent()) {
            Food food = foodOpt.get();
            response.setFoodName(food.getName());
            response.setFoodImage(food.getImage());
        }
        
        // 设置商家信息
        Optional<Merchant> merchantOpt = merchantRepository.findById(activity.getMerchantId());
        if (merchantOpt.isPresent()) {
            Merchant merchant = merchantOpt.get();
            response.setMerchantName(merchant.getName());
            response.setDeliveryFee(merchant.getDeliveryFee() != null ? merchant.getDeliveryFee() : BigDecimal.ZERO);
        }
        
        // 设置发起人信息
        Optional<User> initiatorOpt = userRepository.findById(activity.getInitiatorUserId());
        if (initiatorOpt.isPresent()) {
            response.setInitiatorUsername(initiatorOpt.get().getUsername());
        }
        
        // 设置参与者信息
        List<GroupBuyingParticipant> participants = participantRepository.findByActivityIdOrderByJoinedAtAsc(activity.getId());
        List<GroupBuyingResponse.ParticipantResponse> participantResponses = participants.stream()
            .map(participant -> {
                GroupBuyingResponse.ParticipantResponse participantResponse = 
                    new GroupBuyingResponse.ParticipantResponse(participant);
                // 设置用户信息（用户名、真实姓名、头像）
                Optional<User> userOpt = userRepository.findById(participant.getUserId());
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    participantResponse.setUsername(user.getUsername());
                    participantResponse.setRealName(user.getRealName()); // ⭐ 设置真实姓名
                    participantResponse.setAvatar(user.getAvatar()); // ⭐ 设置头像
                }
                return participantResponse;
            })
            .collect(Collectors.toList());
        response.setParticipants(participantResponses);
        
        // 设置当前用户是否已参与
        if (currentUserId != null) {
            boolean hasJoined = participants.stream()
                .anyMatch(p -> p.getUserId().equals(currentUserId) && !"cancelled".equals(p.getStatus()));
            response.setHasJoined(hasJoined);
        }
        
        return response;
    }
}
